﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Reflection;
using System.ServiceModel.Configuration;
using System.Configuration;

namespace EPS.UI
{
    public class ServiceFactory<T> : IDisposable where T : class
    {
        private EarthChannelFactory<T> m_innerFactory;

        public ServiceFactory()
        { 
            m_innerFactory = new EarthChannelFactory<T>(); 
        }

        public T GetProxy()
        {
            return m_innerFactory.CreateEarthChannel();
        }

        ~ServiceFactory() 
        {
            Dispose(false);
        }

        public void Close()
        {
            Close(TimeSpan.FromSeconds(10));
        }
        public void Close(TimeSpan span)
        {
            if (m_innerFactory != null)
            {
                if (m_innerFactory.State != CommunicationState.Opened) 
                {
                    return;
                } 
                try 
                {
                    m_innerFactory.Close(span); 
                }
                catch (CommunicationException) 
                {
                    m_innerFactory.Abort();
                }
                catch (TimeoutException)
                { 
                    m_innerFactory.Abort(); 
                }
                catch (Exception)
                {
                    m_innerFactory.Abort();
                    throw;
                }
            }
        }


        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                Close();
            }
        }
        void IDisposable.Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
